package xfsale.service.impl.j2ee;

import java.sql.Connection;
import org.apache.log4j.Logger;
import xfsale.exception.AppException;

@SuppressWarnings("unused")
public final class PubRule {

    private Connection conn;
    protected Logger logger = Logger.getLogger(PubRule.class);	//日志

    public PubRule(Connection conn) {
        this.conn = conn;
    }

    public void checkIdcard(String idcard) {
        char verCode[] = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
        int weight[] = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};

        logger.debug("开始验证身份证号码...");

        if (idcard.length() != 15 && idcard.length() != 18) {
            throw new AppException("身份证号码位数不对.");
        }

        String pattern = "^([0-9]{6})(18|19|20)?([0-9]{2})([01][0-9])([0123][0-9])([0-9]{3})([0-9]|X)?$";
        if (!idcard.matches(pattern)) {
            throw new AppException("身份证号码不合法.");
        }

        if (idcard.length() == 18) {
            int sigma = 0;
            for (int i = 0; i < 17; i++) {
                sigma += (idcard.charAt(i) - '0') * weight[i];
            }

            if (verCode[sigma % 11] != idcard.charAt(17)) {
                throw new AppException("身份证号码校验位错误.");
            }
        }

        logger.debug("验证身份证号码成功.");
    }

    public String getBusinessCode(String serviceCode) {
        return serviceCode.substring(1, 4);
    }
}
